package com.bitcat.firstapp.demo.newslistdemo

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivitySwipeRefreshDemoBinding
import com.bitcat.firstapp.demo.netdemo.NewsBean
import com.bitcat.firstapp.demo.netdemo.RetrofitClient
import retrofit2.Call
import retrofit2.Response

class SwipeRefreshDemoActivity : AppCompatActivity() {

    private val binding by lazy {
        ActivitySwipeRefreshDemoBinding.inflate(layoutInflater)
    }

    private val newsAdapter by lazy {
        NewsAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        //通过代码的方式
//        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = newsAdapter

        binding.swipeRefreshLayout.setOnRefreshListener {
            fetchNews()
        }

        //可选 设置颜色
        binding.swipeRefreshLayout.setColorSchemeResources(
            R.color.red,
            R.color.green,
            R.color.blue,
            R.color.yellow
        )


        fetchNews()
        binding.swipeRefreshLayout.isRefreshing = true
    }

    private fun fetchNews() {
        Handler(Looper.getMainLooper()).postDelayed({
            RetrofitClient.newsApi.getNews().enqueue(object : retrofit2.Callback<NewsBean> {
                override fun onResponse(call: Call<NewsBean>, response: Response<NewsBean>) {
                    binding.swipeRefreshLayout.isRefreshing = false
                    //请求失败
                    if (!response.isSuccessful){
                        Log.e("TAG", "onResponse: ${response.code()}")
                        return
                    }

                    //请求成功
                    val newsBean = response.body()
                    newsBean?.let {
                        newsAdapter.updateNews(newsBean.news)
                    }

                }

                override fun onFailure(call: Call<NewsBean>, t: Throwable) {
                    Log.e("TAG", "onResponse: ${t.message}")
                    binding.swipeRefreshLayout.isRefreshing = false
                }
            })
        },5000)
    }
}